package com.device.service;

import com.device.dto.DeviceDTO;
import com.device.dto.SubDeviceDTO;
import com.device.entity.Device;
import com.device.repository.DeviceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class DeviceService {
    
    private static final Logger log = LoggerFactory.getLogger(DeviceService.class);
    
    @Autowired
    private DeviceRepository deviceRepository;
    
    @Autowired
    private SubDeviceService subDeviceService;

    /**
     * 获取所有设备
     * @param email
     * @return
     */
    public List<Device> getAllDevices(String email) {
        log.info("查询所有设备，用户email: {}", email);
        List<Device> devices = deviceRepository.findByEmail(email);
        log.info("查询到设备数量: {}", devices.size());
        return devices;
    }
    
    /**
     * 获取所有设备（嵌套DTO格式）
     * @param email
     * @return
     */
    public List<DeviceDTO> getAllDevicesWithSubDevices(String email) {
        log.info("查询所有设备（嵌套DTO格式），用户email: {}", email);
        List<Device> devices = deviceRepository.findByEmail(email);
        log.info("查询到设备数量: {}, 设备列表: {}", devices.size(), devices);
        
        return devices.stream()
                .map(this::convertToDeviceDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取所有设备（嵌套DTO格式），不按用户过滤
     * @return
     */
    public List<DeviceDTO> getAllDevicesWithSubDevicesNoFilter() {
        log.info("查询所有设备（嵌套DTO格式），不按用户过滤");
        List<Device> devices = deviceRepository.findAll();
        log.info("查询到设备数量: {}, 设备列表: {}", devices.size(), devices);
        
        return devices.stream()
                .map(this::convertToDeviceDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据ID获取设备（嵌套DTO格式）
     * @param id
     * @return
     */
    public Optional<DeviceDTO> getDeviceDTOById(UUID id) {
        log.info("根据ID查询设备（嵌套DTO格式），ID: {}", id);
        return deviceRepository.findById(id)
                .map(this::convertToDeviceDTO);
    }
    
    /**
     * 将Device实体转换为DeviceDTO，并加载子设备信息
     * @param device
     * @return
     */
    private DeviceDTO convertToDeviceDTO(Device device) {
        log.info("转换设备实体为DTO，设备IMEI: {}, ID: {}", device.getDeviceImei(), device.getId());
        DeviceDTO deviceDTO = new DeviceDTO();
        BeanUtils.copyProperties(device, deviceDTO);
        
        try {
            // 获取子设备列表
            log.info("开始获取设备 {} 的子设备列表", device.getDeviceImei());
            List<SubDeviceDTO> subDeviceDTOs = subDeviceService.getSubDeviceDTOsByMainImei(device.getDeviceImei());
            log.info("设备 {} 的子设备数量: {}", device.getDeviceImei(), subDeviceDTOs.size());
            
            if (!subDeviceDTOs.isEmpty()) {
                log.info("设备 {} 的第一个子设备: {}", device.getDeviceImei(), subDeviceDTOs.get(0));
            }
            
            deviceDTO.setSubDevices(subDeviceDTOs);
        } catch (Exception e) {
            log.error("获取设备 {} 的子设备列表时发生错误: {}", device.getDeviceImei(), e.getMessage(), e);
            deviceDTO.setSubDevices(new ArrayList<>());
        }
        
        return deviceDTO;
    }
    
    public Optional<Device> getDeviceById(UUID id) {
        return deviceRepository.findById(id);
    }
    
    public Optional<Device> getDeviceByImei(String deviceImei) {
        return deviceRepository.findByDeviceImei(deviceImei);
    }
    
    public Device createDevice(Device device) {
        device.setId(UUID.randomUUID());
        device.setCreatedTime(System.currentTimeMillis());
        device.setUpdatedTime(System.currentTimeMillis());
        return deviceRepository.save(device);
    }
    
    public Device updateDevice(Device device) {
        device.setUpdatedTime(System.currentTimeMillis());// 更新时间
        return deviceRepository.save(device);
    }
    
    public void deleteDevice(UUID id) {
        deviceRepository.deleteById(id);
    }
    
    public boolean existsByImei(String deviceImei) {
        return deviceRepository.existsByDeviceImei(deviceImei);
    }

    /**
     * 根据设备型号查询设备
     * @param deviceModel
     * @return
     */
    public List<Device> findByDeviceModel(String deviceModel) {
        log.info("根据设备型号查询设备，型号: {}", deviceModel);
        return deviceRepository.findByDeviceModel(deviceModel);
    }
} 